import Cookies from 'js-cookie';
import { actions as modalActions } from '../redux/modules/modal';
import { actions as appActions, LoginStatus } from '../redux/modules/app';
import LoginForm from '@app/components/Form/Login/LoginForm';
import { getLang, isMobile } from './utils';
import JointLoginForm from '@app/components/Form/JointLogin/JointLoginForm';
import { apiToken } from '../services/platform/api';
import moment from 'moment';
import RegisterForm from '@app/components/Form/Register/RegisterForm';
import GameSearch from '@app/components/GameSearch/GameSearch';

export const checkLogin = async () => {
    return new Promise((resolve, reject) => {
        let doRefresh = false;
        const accessToken = getAccessToken();
        const refreshToken = getRefreshToken();

        if (accessToken && refreshToken) {
            // 判断是否快要过期
            const accessTokenExpires = new Date(parseInt(getAccessTokenExpires(), 10)).getTime();
            const timeNow = new Date().getTime();

            // 如果还有1小时就要过期了，那么要刷新
            if (accessTokenExpires - timeNow <= 60 * 60 * 1000) {
                doRefresh = true;
            } else {
                resolve();
            }
        } else if ((!accessToken && !refreshToken) || (accessToken && !refreshToken)) {
            // 未登录
            clearLoginStatus();
            reject();
        } else if (!accessToken && refreshToken) {
            // 有登录态但是已经过期，需要刷新
            doRefresh = true;
        }

        if (doRefresh) {
            refreshUserToken().then(
                () => {
                    resolve();
                },
                () => {
                    // 刷新token失败，清除本地token，按照没有登录态处理
                    clearLoginStatus();
                    reject();
                },
            );
        }
    });
};

export const getRefreshToken = () => {
    return Cookies.get('refresh_token');
};

export const getRefreshTokenExpires = () => {
    return Cookies.get('refresh_token_expires');
};

export const getAccessToken = () => {
    return Cookies.get('access_token');
};

export const getAccessTokenExpires = () => {
    return Cookies.get('access_token_expires') || '0';
};

export const clearLoginStatus = () => {
    Cookies.remove('access_token');
    Cookies.remove('refresh_token');
    Cookies.remove('access_token_expires');
    Cookies.remove('refresh_token_expires');
    window.localStorage.removeItem('tipsChecked');
};

export const checkIfLogin = () => {
    // 如果在个人中心，强制踢回首页
    if (window.location.href.indexOf('/user/') >= 0) {
        window.location.href = '/';
    }
};

export const login = (dispatch: any) => {
    dispatch(
        modalActions.SHOWMODALAction(LoginForm, true, {
            wrapperClassName: 'LoginForm',
        }),
    );
};

export const jointLogin = (
    dispatch: any,
    jointType: string,
    rspCode: string,
    accessTokenThird: string,
    email: string,
) => {
    dispatch(
        modalActions.SHOWMODALAction(JointLoginForm, true, {
            wrapperClassName: 'JointLoginForm',
            jointType,
            rspCode,
            accessTokenThird,
            email,
        }),
    );
};

export const register = (dispatch: any) => {
    dispatch(
        modalActions.SHOWMODALAction(RegisterForm, true, {
            wrapperClassName: 'RegisterForm',
        }),
    );
};

export const logout = (dispatch: any) => {
    clearLoginStatus();
    // 更新用户登录态
    dispatch(appActions.updateLoginStatus(LoginStatus.Unlogin));
};

export const setToken = ({
    accessToken,
    refreshToken,
    exp,
}: {
    accessToken: string;
    refreshToken: string;
    exp: string;
}) => {
    const accessTokenExpireDate = moment(parseInt(exp, 10)).toDate();
    const refreshTokenExpireDate = moment(parseInt(exp, 10)).add(30, 'days').toDate();

    // 用户令牌
    Cookies.set('access_token', accessToken, {
        expires: accessTokenExpireDate,
    });

    Cookies.set('access_token_expires', accessTokenExpireDate.getTime().toString(), {
        expires: accessTokenExpireDate,
    });

    // 用来刷新用户令牌的令牌，设置为30天过期
    Cookies.set('refresh_token', refreshToken, {
        expires: refreshTokenExpireDate,
    });

    Cookies.set('refresh_token_expires', refreshTokenExpireDate.getTime().toString(), {
        expires: refreshTokenExpireDate,
    });
};

export const refreshUserToken = async () => {
    return new Promise((resolve, reject) => {
        apiToken()
            .then((data: any) => {
                if (data.access_token) {
                    setToken({
                        accessToken: data.access_token,
                        refreshToken: data.refresh_token,
                        exp: moment().add(data.expires_in, 'seconds').toDate().getTime().toString(),
                    });

                    resolve();
                } else {
                    console.error('refreshUserToken fail');
                    clearLoginStatus();
                    reject();
                }
            })
            .catch(() => {
                reject();
            });
    });
};

export enum LinkStatus {
    ElementA = 1,
    ElementLink = 2,
    ElementNone = 3,
}

export const getLinkInfo = (params: any) => {
    const lang = getLang();
    const linkType = params.linkType;
    let href = params.link;
    let target = '_self';
    let linkStatus = LinkStatus.ElementNone;

    // 如果没有配置链接，那么说明只是一个纯banner广告
    if (href === '') {
        linkStatus = LinkStatus.ElementNone;
    } else {
        // 需要判断链接是外链还是内链，如果是内链，还要判断往哪里跳转
        if (href.indexOf('gameNo=') >= 0) {
            href = `/${lang}${href}`;
            linkStatus = LinkStatus.ElementLink;
        } else {
            if (linkType === 1) {
                target = '_blank';
                linkStatus = LinkStatus.ElementA;
            } else {
                target = '_self';
                linkStatus = LinkStatus.ElementLink;
            }
        }
    }

    return {
        href,
        target,
        linkStatus,
    };
};

export const showModalSearch = (dispatch: any, type: string) => {
    if (type === 'game') {
        dispatch(
            modalActions.SHOWMODALAction(GameSearch, true, {
                wrapperClassName: 'GameSearch',
            }),
        );
    }
};
